package com.example.music_players

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(), ServiceConnection {
    val TAG = "MainActivity"
    var binder: MusicService.MusicBinder? = null
    val Channel_ID = "my channel"
    val Notification_ID = 1

    private lateinit var seekBar: SeekBar
    private lateinit var textView_mn: TextView
    private lateinit var textView_count: TextView
    private lateinit var button6: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        seekBar = findViewById(R.id.seekBar)
        textView_mn = findViewById(R.id.textView_mn)
        textView_count = findViewById(R.id.textView_count)
        button6 = findViewById(R.id.button6)

        button6.setOnClickListener {
            Log.d(TAG, "Button6 clicked")
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val builder: Notification.Builder
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(Channel_ID, "test", NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(notificationChannel)
                builder = Notification.Builder(this, Channel_ID)
            } else {
                builder = Notification.Builder(this)
            }

            // Create an intent that will bring the user to the MainActivity when clicked
            val intent = Intent(this, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            val pendingIntentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                PendingIntent.FLAG_IMMUTABLE
            } else {
                PendingIntent.FLAG_UPDATE_CURRENT
            }
            val pendingIntent = PendingIntent.getActivity(this, 0, intent, pendingIntentFlags)

            val notification = builder.setSmallIcon(R.drawable.ic_stat_name)
                .setContentTitle("Notification Test")
                .setContentText("This is a test!")
                .setContentIntent(pendingIntent) // Set the pending intent
                .build()
            notificationManager.notify(Notification_ID, notification)
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_MEDIA_AUDIO), 0)
        } else {
            startMusicService()
        }

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}

            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    fun startMusicService() {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.COMMAND, 1)
        startService(intent)
        bindService(intent, this, Context.BIND_AUTO_CREATE)
    }

    fun onPlay(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.COMMAND, 1)
        startService(intent)
    }

    fun onPause(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.COMMAND, 2)
        startService(intent)
    }

    fun onStop(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.COMMAND, 3)
        startService(intent)
    }

    fun onNext(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.COMMAND, 4)
        startService(intent)
    }

    fun onPrev(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.COMMAND, 5)
        startService(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startMusicService()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(this)
    }

    override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
        if (p1 != null) {
            binder = p1 as MusicService.MusicBinder
            thread {
                while (binder != null) {
                    Thread.sleep(1000)
                    runOnUiThread {
                        seekBar.max = binder!!.duration
                        seekBar.progress = binder!!.currentPosition
                        textView_mn.text = binder!!.musicName // 显示歌曲标题
                        textView_count.text = "${binder!!.currentIndex + 1}/${binder!!.size}"
                    }
                }
            }
        }
    }

    override fun onServiceDisconnected(p0: ComponentName?) {
        binder = null
    }
}